package durst.data;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import com.sdicons.json.mapper.JSONMapper;

import durst.data.dao.impl.FileAccessDao;
import durst.data.json.FileJSONHelper;

@DatabaseTable(tableName = "File", daoClass = FileAccessDao.class)
public class FileAccess extends CSDEntity {
	public static final String OWNER_ID = "owner_id";
	public static final String EVENT_ID = "event_id";
	public static final String NAME = "name";
	
	static {
		JSONMapper.addHelper(new FileJSONHelper());
	}
	
	@DatabaseField(generatedId = true)
	private int id; 
	
	@DatabaseField(canBeNull = false, foreign = true, columnName = OWNER_ID)
	private Account owner; 
	
	@DatabaseField(foreign = true, columnName = EVENT_ID) 
	private Event event; 
	
	@DatabaseField(canBeNull = false, columnName = NAME)
	private String name;
	
	public FileAccess() {}

	public FileAccess(Account account, Event event, String fileName) {
		this.owner = account;
		this.event = event;
		this.name = fileName;
	}
	
	public boolean hasAccess(Account user) {
		return hasAccess(user, event, owner);
	}
	
	public static boolean hasAccess(Account user, Event event, Account owner) {
		if (event != null && !user.equals(owner)) {
			for (Invite invite : user.getInvitedTo())
				if (invite.getEvent().equals(event)) 
					return true;
			return false;
		}

		return true;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public Account getOwner() {
		return owner;
	}

	public void setOwner(Account owner) {
		this.owner = owner;
	}

	public Event getEvent() {
		return event;
	}

	public void setEvent(Event event) {
		this.event = event;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}
}
